package blue.global.util;

import java.lang.reflect.Field;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;

/**
 * 用 XML 序列化对象
 * 
 * @author zhengj
 * @since 2009-1-5 1.0
 */
public class XmlUtil
{

	/**
	 * 用 XML 序列化对象
	 * 
	 * @param obj 对象
	 * @param field 字段名，不定参数
	 * @return XML序列化字符串
	 */
	public static String toXml(Object obj, String... field)
	{
		Object value = null;
		Class<?> cls = obj.getClass();
		Field[] fields = cls.getDeclaredFields();
		Field.setAccessible(fields, true);

		StringBuilder sb = new StringBuilder();
		sb.append("<").append(cls.getSimpleName());

		if (field.length == 0)
		{
			for (Field f : fields)
			{
				sb.append(" ").append(f.getName()).append("=\"");
				try
				{
					value = f.get(obj);
					sb.append(value == null ? "" : value);
				}
				catch (Exception e)
				{
					e.printStackTrace();
				}
				sb.append("\"");
			}
		}
		else
		{
			List<String> fieldList = Arrays.asList(field);

			for (Field f : fields)
			{
				if (!fieldList.contains(f.getName()))
				{
					continue;
				}

				sb.append(" ").append(f.getName()).append("=\"");
				try
				{
					value = f.get(obj);
					sb.append(value == null ? "" : value);
				}
				catch (Exception e)
				{
					e.printStackTrace();
				}
				sb.append("\"");
			}
		}
		sb.append("/>\n");
		return sb.toString();
	}

	/**
	 * 用 XML 序列化对象列表
	 * 
	 * @param beans 对象列表
	 * @return XML 序列化字符串
	 */
	public static String toXml(Collection<?> beans, String... field)
	{
		StringBuilder sb = new StringBuilder();
		if (beans != null)
		{
			for (Object obj : beans)
			{
				sb.append(toXml(obj, field));
			}
		}
		return sb.toString();
	}

	/**
	 * 创建客户端信息
	 * 
	 * @param info 信息内容
	 * @param state 信息状态
	 * @param beanXml 对象列表
	 * @return 客户端信息
	 */
	public static String toXml(String info, boolean state, Collection<?> beans,
			String... field)
	{
		StringBuilder sb = new StringBuilder();
		sb.append("<root info=\"").append(info).append("\" ");
		sb.append("state=\"").append(state).append("\">");
		sb.append(toXml(beans, field));
		sb.append("</root>");
		return sb.toString();
	}
}
